#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include <iostream>
#include <functional>
#include "include/muduo/base/CountDownLatch.h"
class translateclient
{
public:
    translateclient(const std::string &ipr, int port)
        : _cout(1), _client(_event.startLoop(), muduo::net::InetAddress(ipr, port), "translateclient")
    {
        _client.setConnectionCallback(std::bind(&translateclient::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&translateclient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }
    void connect() // 链接服务器，需要阻塞等待连接成功后再返回
    {
        _client.connect();
        _cout.wait();//阻塞
    }
    bool send(const std::string &as) // 发送数据
    {
        if (_ptr->connected() == true)
        {
            _ptr->send(as);
            return true;
        }
        else
        {
            return false;
        }
    }
    ~translateclient()
    {
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn) // 连接服务器成功后调用的回调函数
    {
        if (conn->connected())
        {
            _cout.countDown();//唤醒主线程
            _ptr=conn;
        }
        else
        {
            _ptr.reset();//链接失败，关闭连接
        }

    }
    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buff, muduo::Timestamp) // 得到应答后调用的回调函数
    {
        std::cout<<"翻译结果"<<buff->retrieveAllAsString()<<std::endl;
    }

private:
    muduo::net::EventLoopThread _event; // 内部自动创建子线程进行事件检测
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _ptr; // 连接的信息
    muduo::CountDownLatch _cout;       // 保证同步机制
};
int main()
{
    translateclient as("127.0.0.1", 8080);
    as.connect();
    while (1)
    {
        std::string buff;
        getline(std::cin, buff);
        as.send(buff);
    }
    return 0;
}